// #ifdef MP
const saveMp4 = (url, progress, down = true, back) => {

	uni.getSetting({
		success: (res) => {
			//检查是否有访问相册的权限，如果没有则通过wx.authorize方法授权
			let auth = 'scope.writePhotosAlbum';
			// #ifdef MP-TOUTIAO
			auth = 'scope.album';
			// #endif
			if (!res.authSetting[auth]) {
				console.log('没有获取授权');
				uni.authorize({
					scope: auth,
					success: (res) => {
						//用户点击允许获取相册信息后进入下载保存逻辑
						save(url, progress, down, back)
					},
					fail(ret) {
						wx.getPrivacySetting({
							success: res => {
								if (!res.needAuthorization) {
									uni.showModal({
										content: '检测到您未打开保存相册权限，无法保存，是否去设置打开？',
										confirmText: "确认",
										cancelText: '取消',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting({
													success: (
														res
													) => {
														console
															.log(
																res
															);
													}
												})
											} else {
												progress(false);
												uni.showToast({
													title: '保存失败',
													icon: "none"
												})
											}
										}
									})
								}
							},
							fail: () => {
								uni.showToast({
									title: '保存失败',
									icon: "none"
								})
							},
							complete: () => {}
						})
					}
				})
			} else {
				console.log('已获取授权');
				save(url, progress, down, back)
			}
		}
	});


}

const save = (url, progress, down = true, back) => {
	/* uni.showLoading({
		title: "正在保存",
		mask: true
	}); */
	if (down) {
		let filepath = wx.env.USER_DATA_PATH + '/' + new Date().valueOf() + '.mp4'
		const downloadTask = uni.downloadFile({
			url: url,
			timeout:300000,
			filepath:filepath,
			success: (res) => {
				if (res.statusCode === 200) {
					console.log(res)
					uni.saveVideoToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function() {
							uni.hideLoading()
							uni.showToast({
								title: "保存成功",
								icon: "none"
							});
						},
						fail: function(e) {
							uni.hideLoading()
							console.log(e)
							uni.showToast({
								title: "保存失败",
								icon: "none"
							});
						}
					});
				}
			},
			fail(e) {
				console.log(e)
				uni.hideLoading()
				if (back) {
					back(500)
				} else {
					uni.showToast({
						title: "保存失败，请稍后重试",
						icon: "none"
					});
				}
			}
		});

		downloadTask.onProgressUpdate((res) => {
			if (progress) {
				progress(res);
			} else {
				console.log('下载进度' + res.progress);
				console.log('已经下载的数据长度' + res.totalBytesWritten);
				console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
			}

		});
	} else {
		uni.saveVideoToPhotosAlbum({
			filePath: url,
			success: function() {
				uni.hideLoading()
				uni.showToast({
					title: "保存成功",
					icon: "none"
				});
			},
			fail: function(e) {
				uni.hideLoading()
				console.log(e)
				uni.showToast({
					title: "保存失败",
					icon: "none"
				});
			}
		});
	}
}
const saveMp3 = null;
// #endif
// #ifdef H5
const saveMp4 = null;
const saveMp3 = null;
// #endif

// #ifdef APP-PLUS
const saveMp4 = (url, progress, down = true, back) => {
	if (!url) {
		uni.showToast({
			title: "保存失败:缺少地址",
			icon: "none"
		});
		return false;
	}

	/* uni.showLoading({
		title: "正在保存",
		mask: true
	}); */
	if (down) {
		const downloadTask = uni.downloadFile({
			url: url,
			timeout:300000,
			success(res) {
				if (res.statusCode == 200) {
					uni.saveImageToPhotosAlbum({ //保存
						filePath: res.tempFilePath,
						success(saveImgRes) {
							uni.hideLoading()
							// 手机会自动保存到系统相册，电脑可以自己选择保存的地址
							uni.showToast({
								title: "保存成功",
								icon: "none"
							});
						},
						fail: function(e) {
							console.log(e)
							uni.hideLoading()
							uni.showToast({
								title: "保存失败",
								icon: "none"
							});
						}
					});
				}
			},
			fail: function(e) {
				console.log(e)
				uni.hideLoading()
				uni.showToast({
					title: "保存失败，请稍后重试",
					icon: "none"
				});
			}
		})

		downloadTask.onProgressUpdate((res) => {
			if (progress) {
				progress(res);
			} else {
				console.log('下载进度' + res.progress);
				console.log('已经下载的数据长度' + res.totalBytesWritten);
				console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
			}
		});
	} else {
		uni.saveImageToPhotosAlbum({ //保存
			filePath: url,
			success() {
				uni.hideLoading()
				// 手机会自动保存到系统相册，电脑可以自己选择保存的地址
				uni.showToast({
					title: "保存成功",
					icon: "none"
				});
			},
			fail: function(e) {
				console.log(e)
				uni.hideLoading()
				uni.showToast({
					title: "保存失败",
					icon: "none"
				});
			}
		});
	}

}
const saveMp3 = function(url, progress) {
	if (!url) {
		uni.showToast({
			title: "保存失败:缺少地址",
			icon: "none"
		});
		return false;
	}
	console.log("url==>", url);
	uni.showLoading({
		title: '保存视频中'
	})
	const downloadTask = uni.downloadFile({
		url: url,
		timeout:300000,
		success(res) {
			if (res.statusCode == 200) {
				var root = plus.io.convertLocalFileSystemURL("_www/");
				var doc = plus.io.convertLocalFileSystemURL("_doc/");
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success: function(save) {
						uni.getSystemInfo({
							success: (res) => {
								if (res.osName == "ios") {
									var mp3Dir = doc + save.savedFilePath.replace(
										"_doc\/", "/");
									var imgDir = root + "/static/video.jpg";
									var audioModule = uni.requireNativePlugin(
										"iOSAudioPlugin");
									audioModule.compositionVideoWithImagesAndAudio({
											'images': [imgDir],
											'videoName': 'outVideo.mov',
											'audioPath': mp3Dir,
										},
										(dir) => {
											saveToImage(dir);
										})
								} else {
									var mp3Dir = doc + save.savedFilePath.replace(
										"_doc\/", "");
									var imgDir = root + "static/video.jpg";
									var duration = 200; //时间
									var mp4Dir = root + "static/test.mp4";

									console.log("res------mp3Dir-->", mp3Dir);
									console.log("res------imgDir-->", imgDir);
									console.log("res------mp4Dir-->", mp4Dir);

									var audioModule = uni.requireNativePlugin(
										"FFmpegModule");
									var cmd = ' -r 15 -f image2 -loop 1 -i ' +
										imgDir + ' -i ' + mp3Dir +
										' -s 360x240 -pix_fmt yuvj420p -t ' +
										duration + ' -vcodec libx264  -y ' + mp4Dir;
									audioModule.runCmd(cmd, function(res) {
										console.log("==============>", res);
										if (res.code == 200) {
											saveToImage(mp4Dir);
										}
									});
								}
							}
						})




					}
				})

				/* */
				console.log("root=====>", root);
				console.log("doc============>", doc);
				//执行指令				
			}
		},
		fail: function(e) {
			console.log(e)
			uni.hideLoading()
			uni.showToast({
				title: "保存失败，请稍后重试",
				icon: "none"
			});
		}
	})
	const saveToImage = function(dir) {
		uni.saveImageToPhotosAlbum({
			filePath: dir,
			success: function() {
				uni.hideLoading()
				uni.showToast({
					title: "保存成功"
				})
			},
			fail: function(e) {
				console.log(e)
				uni.hideLoading()
				uni.showToast({
					title: "保存失败",
					icon: "none"
				});
			}

		})
	}

	downloadTask.onProgressUpdate((res) => {

		console.log('下载进度' + res.progress);
		console.log('已经下载的数据长度' + res.totalBytesWritten);
		console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);

	});

}
// #endif
export {
	saveMp4,
	saveMp3
}